package com.easymall.web;

import com.easymall.service.CategoryService;
import com.easymall.util.BaseFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "CategoryDeleteServlet")
public class CategoryDeleteServlet extends HttpServlet {
    private CategoryService categoryService;

    @Override
    public void init() throws ServletException {
        try {
            categoryService = BaseFactory.getFactory().getInstance(CategoryService.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取分类的id
        String cidString = request.getParameter("cid");
        String msg = null;
        try{
            int cid = Integer.valueOf(cidString);
            // 2、验证分类是否存在
            if (null == msg) {
                boolean isExist = categoryService.hasCategoryById(cid);
                if (!isExist) {
                    msg = "分类不存在！";
                } else {
                    // 3、删除分类
                    boolean isSucces = categoryService.deleteCategory(cid);
                    if (isSucces) {
                        msg = "true";
                    } else {
                        msg = "删除失败！";
                    }
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            msg = "参数错误！";
        } catch (SQLException e) {
            e.printStackTrace();
            msg = "删除失败，请稍候重试！";
        }

        // 4、响应
        response.getWriter().write(msg);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
